/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managed.util;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;

/**
 *
 * @author Danilo
 */
public class ImageUtil {

    private static final int IMG_WIDTH = 120;
    private static final int IMG_HEIGHT = 200;

    public ImageUtil() {
    }

    public static InputStream resizeImage(InputStream is) throws IOException {
        BufferedImage originalImage = ImageIO.read(is);

        BufferedImage scaledImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.SCALE_SMOOTH);
        Graphics2D graphics2D = scaledImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        graphics2D.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        graphics2D.dispose();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(scaledImage, "jpg", os);
        return new ByteArrayInputStream(os.toByteArray());
    }

    public static byte[] InputStreamToByte(InputStream fis) throws FileNotFoundException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        byte[] buf = new byte[1024];

        try {

            for (int readNum; (readNum = fis.read(buf)) != -1;) {

                bos.write(buf, 0, readNum);
            }
            byte[] bytes = bos.toByteArray();
            return bytes;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
